package com.bwsoft.portal.service.impl;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;

import com.bwsoft.admin.domain.Account;
import com.bwsoft.admin.domain.Standard;
import com.bwsoft.api.pojo.ResponsePojo;
import com.bwsoft.api.util.Constant;
import com.bwsoft.domain.User;
import com.bwsoft.portal.domain.valueObject.StandardListVO;
import com.bwsoft.portal.domain.valueObject.StandardVO;
import com.bwsoft.portal.service.StandardService;
import com.bwsoft.service.DictionaryDataService;
import com.bwsoft.util.Base64Util;
import com.bwsoft.util.DesUtil;
import com.bwsoft.util.UploadFileUtil;

@Service(StandardService.NAME)
public class StandardServiceImpl extends PortalBaseServiceImpl implements StandardService{
	private static Logger LOG = Logger.getLogger(RegisterServiceImpl.class);
	
	@Resource(name =  DictionaryDataService.NAME)
	DictionaryDataService dictionaryDataService;
	
	@Override
	public List<StandardListVO> getListVo(List<Standard> standards) throws Exception {
		List<StandardListVO> standardListVo = new ArrayList<StandardListVO>();
		StandardListVO standardVo = new StandardListVO();
		for (Standard standard : standards) {
			standardVo = new StandardListVO();
			standardVo.setAddTime(standard.getAddTime());
			standardVo.setStandardName(standard.getStandardName());
			standardVo.setFilePath("api/jsp/pdf.jsp?r="+Base64Util.getBase64(DesUtil.encrypt("fileid="+standard.getFile().getId(), Constant.KEY_DES).getBytes("utf-8")));
			standardListVo.add(standardVo);
		}
		return standardListVo;
	}
	
	@Override
	public List<Standard> findData(Integer page, Integer rows, String s_type,
			String s_field, String s_standardName, String s_status, String showType, Integer uploader) {
		StringBuffer standardHql = new StringBuffer();
		Map<String, String> fieldMap=dictionaryDataService.getDicDataByName("standard_field");
		Map<String, String> typeMap=dictionaryDataService.getDicDataByName("standard_type");
		Map<String, String> statusMap=dictionaryDataService.getDicDataByName("audit_status");
		standardHql.append("from Standard as std where 1=1");
		if(s_type != null && !"".equals(s_type.trim()) && !"-1".equals(s_type.trim())){
				standardHql.append("and std.type = '"+s_type.trim()+"'");
		}
		if(s_field != null && !"".equals(s_field.trim()) && !"-1".equals(s_field.trim())){
			standardHql.append("and std.field = '"+s_field.trim()+"'");
		}
		if(s_standardName != null && !"".equals(s_standardName.trim())){
			standardHql.append("and std.standardName like '%"+s_standardName.trim()+"%'");
		}
		if(s_status != null && !"".equals(s_status.trim()) && !"-1".equals(s_status.trim())){
			standardHql.append("and std.status = '"+s_status.trim()+"'");
		} else if (!"1".equals(showType)) {
			standardHql.append("and std.status = 1");
		}
		if (uploader != null && "1".equals(showType)) {
			standardHql.append(" and std.uploader.accountId=" + uploader);
		} else if (!"1".equals(showType)) {
			standardHql.append(" and std.displayStatus = 1");
		}
		standardHql.append(" order by std.addTime desc");
		List<Standard> standardData=standardDao.findPage(standardHql.toString(), rows, (page - 1) * rows);
		for (Standard standard : standardData) {
			standard.setFieldName(fieldMap.containsKey(standard.getField().toString())?fieldMap.get(standard.getField().toString()):"");
			standard.setTypeName(typeMap.containsKey(standard.getType().toString())?typeMap.get(standard.getType().toString()):"" );
			standard.setStatusName(statusMap.containsKey(standard.getStatus().toString())?statusMap.get(standard.getStatus().toString()):"");
		}
		
		return standardData;
	}
	
	@Override
	public long getCount(String s_type,	String s_field, String s_standardName, String s_status, String showType, Integer uploader) {
		StringBuffer standardHql = new StringBuffer();
		standardHql.append("select count(*) from Standard as std where 1=1 ");
		if(s_type != null && !"".equals(s_type.trim())){
				standardHql.append(" and std.type = '"+s_type.trim()+"'");
		}
		if(s_field != null && !"".equals(s_field.trim())){
			standardHql.append(" and std.field = '"+s_field.trim()+"'");
		}
		if(s_standardName != null && !"".equals(s_standardName.trim())){
			standardHql.append(" and std.standardName like '%"+s_standardName.trim()+"%'");
		}
		if(s_status != null && !"".equals(s_status.trim())){
			standardHql.append(" and std.status = '"+s_status.trim()+"'");
		}
		if (uploader != null && "1".equals(showType)) {
			standardHql.append(" and std.uploader.accountId=" + uploader);
		} else if (!"1".equals(showType)) {
			standardHql.append(" and std.displayStatus = 1");
		}
		return (Long)standardDao.findByHql(standardHql.toString()).get(0);
	}
	
	@Override
	public ResponsePojo saveOrUpdateStandard(String standardName, Account account,
			String field, String type, File stdfile, String stdfileName) {
		Standard standard = new Standard();
		ResponsePojo rp = new ResponsePojo();
		com.bwsoft.admin.domain.File filePojo = new com.bwsoft.admin.domain.File();
		try {
			standard.setAddTime(new Date());
			//---------附件上传（如果没上传则取原数据库内容保存）--------------
			if(stdfile != null && !"".equals(stdfile)){
				Calendar now = Calendar.getInstance();
				String stdFilepath = ServletActionContext.getServletContext().getRealPath(Constant.PATH_PDF_STANDARD+"/"+now.get(Calendar.YEAR)+(now.get(Calendar.MONTH) + 1));
				String newFileName=null ;
				newFileName=UUID.randomUUID().toString()+stdfileName.substring(stdfileName.lastIndexOf('.'), stdfileName.length());
				UploadFileUtil.uploadOneFile(newFileName, stdfile, stdFilepath);
				filePojo.setPath(Constant.PATH_PDF_STANDARD+"/"+now.get(Calendar.YEAR)+(now.get(Calendar.MONTH) + 1)+"/"+newFileName);
				filePojo.setName(stdfileName);
				filePojo.setSize(String.valueOf(stdfile.length()));
				filePojo.setAddTime(new Date());
				standard.setFile(filePojo);
			}
			standard.setUploader(account);
			standard.setField(Integer.valueOf(field));
			standard.setType(Integer.valueOf(type));
			standard.setStatus(0);
			standard.setDisplayStatus(false);
			standard.setHtscFlag(false);
			standard.setStandardName(standardName);
			standard.setHtUploader((User)ServletActionContext.getRequest().getSession().getAttribute("User"));
			standardDao.saveOrUpdate(standard);
			rp.setErrcode(0);
			rp.setErrmsg("保存成功！");
		} catch (Exception e) {
			rp.setErrcode(5);
			rp.setErrmsg("保存失败：" + e.toString());
			LOG.info(e);
		}
		return rp;
	}

	@Override
	public List<StandardVO> getVo(List<Standard> standards) throws Exception {
		List<StandardVO> standardListVo = new ArrayList<StandardVO>();
		StandardVO standardVo = new StandardVO();
		for (Standard standard : standards) {
			standardVo = new StandardVO();
			standardVo.setAddTime(standard.getAddTime());
			standardVo.setStandardId(standard.getStandardId());
			standardVo.setFieldName(standard.getFieldName());
			if(standard.getFile() != null && !"".equals(standard.getFile())){
				standardVo.setFilePath("api/jsp/pdf.jsp?r="+Base64Util.getBase64(DesUtil.encrypt("fileid="+standard.getFile().getId(), Constant.KEY_DES).getBytes("utf-8")));
			}
			standardVo.setStandardName(standard.getStandardName());
			standardVo.setStatusName(standard.getStatusName());
			standardVo.setTypeName(standard.getTypeName());
			standardVo.setDisplayStatus(standard.getDisplayStatus());
			standardListVo.add(standardVo);
		}
		return standardListVo;
	}
}
